package ks.server.controllers.commands.admin.user;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.user.User;
import ks.server.ipc.Listener;
import ks.server.persist.PersistentUserManager;
import ks.server.ServerContext;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * Process command to unblock a user.
 * 
 * @author Christopher Page
 */
public class UserUnblockController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public UserUnblockController (Communicator com) {
		this.com = com;
	}
	
	/**
	 * Process the message
	 * 
	 * @param m The message to process.
	 * @return A boolean value.
	 */
	public boolean process(Message m) {

		PersistentUserManager um = ServerContext.getUserManager();
		
		if (um.getUser(m.getOriginator()) == null) {
			Listener.nack(m, 4, "Unable to unblock user: what!? I don't even...");
			return true;
		}
		if (!um.getUser(m.getOriginator()).isAdmin()) {
			Listener.nack(m, 4, "Unable to unblock user: access denied.");
			return true;
		}
		
		Node userUnlock = m.contents();
		
		// Find out its attributes.
		NamedNodeMap nnp = userUnlock.getAttributes();
		
		// null on missing attr
		Node playerNode = nnp.getNamedItem("player");
		
		String player;
		
		if (playerNode != null) {
			player = playerNode.getNodeValue();
		}
		else {
			Listener.nack(m, 4, "Unable to unblock user: no user specified.");
			return true;
		}
		
		User u = um.getUser(player);
		
		if (u == null) {
			Listener.nack(m, 4, "Unable to unblock user: user does not exist.");
			return false;
		}
		
		u.setBlocked(false);
		um.updateUser(player);
		
		Listener.ack(m, "User unblocked.");
		
		return true;
	}
}
